from django.conf import settings
from django.contrib.sessions.models import Session
from django.utils.cache import patch_vary_headers
from django.contrib.sessions.middleware import SessionWrapper
import datetime

class SessionMiddleware(object):
    # copy of django.contrib.sessions.middleware.SessionMiddleware
    def process_request(self, request):
        request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None))

    def process_response(self, request, response):
        # If request.session was modified, or if response.session was set, save
        # those changes and set a session cookie.
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                session_key = request.session.session_key or Session.objects.get_new_session_key()
                # changed part, check if login form was posted and if user wants persistent cookie
                short_login = True
                if request.POST and request.POST.has_key("do_login"):
                    remember = request.POST.get("remember", None)
                    if request.user.is_authenticated() and remember:
                        short_login = False
                if short_login:
                    max_age = None
                    expires = None
                else:
                    max_age = settings.SESSION_COOKIE_AGE
                    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
                new_session = Session.objects.save(session_key, request.session._session,
                    datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))
                response.set_cookie(settings.SESSION_COOKIE_NAME, session_key,
                    max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                    secure=settings.SESSION_COOKIE_SECURE or None)
        return response